using System;
using Dimebrain.TweetSharp;
using Dimebrain.TweetSharp.Extensions;
using Dimebrain.TweetSharp.Fluent;
using Peepster.Core;

namespace Peepster.Infrastructure.Twitter
{
    public class TweetSharpTwitterService : ITwitterService
    {
        private IFluentTwitter _service;

        public TweetSharpTwitterService()
        {
            _service = FluentTwitter.CreateRequest(GetClientInfo());
        }

        private TwitterClientInfo GetClientInfo()
        {
            var clientInfo = new TwitterClientInfo
            {
                ClientName = AppSettings.ClientName,
                ClientUrl = AppSettings.ClientUrl,
                ConsumerKey = AppSettings.ConsumerKey,
                ConsumerSecret = AppSettings.ConsumerSecret
            };

            return clientInfo;
        }

        public bool ValidateAccount(string userName, string password)
        {
            _service.AuthenticateAs(userName, password)
                .Statuses()
                .Mentions()
                .AsJson();

            return _service.Request().AsError() == null;
        }


        public void SendTweet(string message)
        {
            try
            {
                _service
                    .Configuration.UseUrlShortening(ShortenUrlServiceProvider.TinyUrl)
                    .AuthenticateAs(AppSettings.TwitterUserName, AppSettings.TwitterPassword)
                    .Statuses().Update(message)
                    .AsJson();

                var response = _service.Request();

                if (response.AsStatuses() == null)
                {
                    var error = response.AsError();
                    if (error != null)
                        throw new ApplicationException(error.ErrorMessage);
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException("Unable to send tweet\n" + e.Message, e);
            }
        }
    }
}